package util;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;

public class GetParamToClass {


    public static Object setObjectFiled(HttpServletRequest request, Class<?> _class) {
        Enumeration en = request.getParameterNames();
        Field[] fields = _class.getDeclaredFields();
        if (_class == null) {
            return null;
        }
        try {
            Object object = _class.newInstance();
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String beanSetMethod = "set" + captureName(paramName);
                for (Field field : fields) {
                    if (paramName.equals(field.getName())) {
                        String typeClass = field.getType().getSimpleName().toString();
                        if (typeClass.equals("Integer")) {
                            _class.getMethod(beanSetMethod, Integer.class).invoke(object, Integer.valueOf(request.getParameter(paramName)));
                            break;
                        } else if (typeClass.equals("String")) {
                            _class.getMethod(beanSetMethod, String.class).invoke(object, request.getParameter(paramName));
                            break;
                        }
                    }
                }
            }
            return object;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String captureName(String name) {
        char[] cs = name.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);

    }

}
